'use strict';
app.controller('houseOwnerroleInfoCtl', function($scope,$http,rest,$compile,$location,ngDialog,user,$state,$window,uiLoad,$rootScope,$ocLazyLoad) {
    var token = $window.localStorage.getItem("token");
    
    //方法级权限
    var accessStr = $window.localStorage.getItem("accessStr");
    $scope.btns = {
    	add: 'innjia',  //新建
    	delete: 'innjia',  //删除
    	edit: 'innjia',  //编辑
    	jurisdiction: 'innjia',  //权限分配
    	resetPasswords: 'innjia',  //重置密码
    	addmember: 'innjia',  //添加成员
    	exportExcel: 'innjia', //导出表格
    	batchExportImg: 'innjia',  //批量导出图片
    	details: 'innjia',  //详情
    	rent: 'innjia',  //租赁PDF
    	list: 'innjia'  //列表
    }
    //延迟执行 - 当左侧菜单生产完毕再获取当前菜单的ID 利用ui-sref-active有且只有一个active即当前的特性用jq去获取预先存储在菜单上的id
    user.response().then(function(res){
    	var nowId = $(document).find(".navItem.active").attr("data-id");
    	rest.decoJava({
		   	 type: "post",
		     url: "/tenancy-sys/admin/menu/detail/"+nowId,
		     data: "",
		     //contentType:"application/json",
		     beforeSend: function(request){
				request.setRequestHeader("token", token); 
			},
		    success: function(data){ 
		    	console.log(data)
			    if(data.code == "0000"){
				    //匹配权限
				    angular.forEach(data.result.menuMethods,function(data){
				    	if(data.methodTagName == "add"){
				    		$scope.btns.add = data.id;
				    	} else if(data.methodTagName == "delete"){
				    		$scope.btns.delete = data.id;
				    	} else if(data.methodTagName == "edit"){
				    		$scope.btns.edit = data.id;
				    	} else if(data.methodTagName == "jurisdiction"){
				    		$scope.btns.jurisdiction = data.id;
				    	} else if(data.methodTagName == "resetPasswords"){
				    		$scope.btns.resetPasswords = data.id;
				    	} else if(data.methodTagName == "addmember"){
				    		$scope.btns.addmember = data.id;
				    	} else if(data.methodTagName == "exportExcel"){
				    		$scope.btns.exportExcel = data.id;
				    	} else if(data.methodTagName == "batchExportImg"){
				    		$scope.btns.batchExportImg = data.id;
				    	} else if(data.methodTagName == "details"){
				    		$scope.btns.details = data.id;
				    	} else if(data.methodTagName == "rent"){
				    		$scope.btns.rent = data.id;
				    	} else if(data.methodTagName == "list"){
				    		$scope.btns.list = data.id;
				    	}
				    })
			    } else if(data.message == "菜单Id有误！！！"){
			    	// $window.location.reload();
			    } else{
			    	layer.msg(data.message+'请刷新试试', {
			        	offset:'t',
			        	icon: 2
					});
			    }
		    }
	    });

    })
    
	//初始化获取所有角色
	rest.decoJava({
       	type: 'POST',
        url: '/tenancy-sys/admin/role/all/list',
        data: "",
       	beforeSend: function(request){
			request.setRequestHeader("token", token); 
		},
        success: function(data){
            $scope.upRoleDatas = data.result;
            $scope.upRoleDatas.unshift({roleName: "所属角色", id: ""});
            $scope.upRole = $scope.upRoleDatas[0];
            $scope.$apply();
        }
    })
	
	//自定义方法状态数据
	$scope.methodsStatus = [
	        {
	            "status" : "AVAILABLE",
	            "menuName" : "可用"
	        },
	        {
	            "status" : "FORBID",
	            "menuName" : "禁止"
	        },
	        {
	            "status" : "DELETE",
	            "menuName" : "删除"
	        },
	        {
	            "status" : "",
	            "menuName" : "全部"
	        }
	    ];
	$scope.itemStatus = $scope.methodsStatus[0]; //默认为可用
	
    var tabHeight = ($window.innerHeight - 268)+"px"; //table内容区高度
    $scope.dataTableSettingRoles = {
        "sAjaxSource": "/tenancy-sys/admin/role/list",
        // "dom": "tipr",
        "bFilter": true,  //搜索	
         "sScrollY": tabHeight,  //给定高度，内容超出即出滚动条
         "bScrollCollapse": false,  //不管内容多少高度固定
         "aLengthMenu": [25,50,100,200],
         "iDisplayLength": 25,
         "sDom": '<"top">rt<"bottom"lip><"clear">', //位置 l-每页显示数量,f-过滤输入,t-表单Table,i-信息,p-翻页
         "bAutoWidth": true,  //自适应列宽
        "aoColumns": [
        	{
        		"mDataProp": "",
                "sDefaultContent": "",
                "sClass": "center handle-ck"
        	},
            {
                "mDataProp": "roleName",
                "sTitle": "角色名称",
                "sDefaultContent": "",
                "sClass": "center failure"
            }, {
                "mDataProp": "upRoleName",
                "sTitle": "所属角色",
                "sDefaultContent": "",
                "sClass": "center handle-upMenu"
            }, 
            {
                "mDataProp": "",
                "sTitle": "角色等级",
                "sDefaultContent": "",
                "sClass": "center menu-grade"
            },
            {
                "mDataProp": "",
                "sTitle": "角色状态",
                "sDefaultContent": "",
                "sClass": "center menuStatus"
            },
            {
                "mDataProp": "remark",
                "sTitle": "备注",
                "sDefaultContent": "",
                "sClass": "center"
            },
            {
                "mDataProp": "createTime",
                "sTitle": "创建时间",
                "sDefaultContent": "",
                "sClass": "center"
            },{
                "mDataProp": "operate",
                "sTitle": "操作",
                "sDefaultContent": "",
                "sClass": "center handle-td"
            }
        ],
        "fnRowCallback": function(nRow, aData, iDisplayIndex) {
            var btnStr = "";
            btnStr += " <a class='operation-btn'>\
                                <img src='img/operation.png' width='20px' height='20px' />\
                                <div class='operation-none' >\
                                    <dl class='operation oper-triangle'>\
                                        <dd><a href='javascript:;' data-btn='btns.edit' ng-click='decorateModify(\"" + iDisplayIndex + "\",$event)'>编辑</a></dd>\
                                        <dd><a href='javascript:;' data-btn='btns.jurisdiction' ng-click='decorateModify2($event, \"" + iDisplayIndex + "\")'>分配权限</a></dd>\
                                        <dd><a href='javascript:;' data-btn='btns.addmember' ng-click='decorateModify3($event, \"" + iDisplayIndex + "\")'>成员</a></dd>\
                                        <span class='z'>▲</span><span class='y'>▲</span>\
                                    </dl>\
                                </div>\
                            </a>";

                $(nRow).find(".handle-td").append($compile(btnStr)($scope));

                /*$(nRow).find(".operation-btn").on('click', function(ev) {
                	ev.stopPropagation();
                	$(".operation-none").hide();
                    var sopt = $(this).parent().find(".operation-none");
                    if (sopt.css('display') == 'none') {
                        sopt.show();
                        //$scope.isCoverBgShow = true;
                        //$scope.$apply();
                    } else {
                        sopt.hide();
                        //$scope.isCoverBgShow = false;
                        //$scope.$apply();
                    }
                });*/
            // btnStr += "<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' data-btn='btns.bj' ng-click='decorateModify(\"" + iDisplayIndex + "\",$event)'>编辑</a>"
            // 			+"<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' data-btn='btns.gn' ng-click='decorateModify2($event, \"" + iDisplayIndex + "\")'>分配权限</a>"
            // 			+"<a href='javascript:;' class='btn btn-yellow' style='margin-right:10px;' data-btn='btns.cy' ng-click='decorateModify3($event, \"" + iDisplayIndex + "\")'>成员</a>";
            // $(nRow).find(".handle-td").append($compile(btnStr)($scope));
            
            var checkStr = "";
            checkStr += '<input type="checkbox" data-index="'+iDisplayIndex+'" value="'+$scope.myDatas.result[iDisplayIndex].id+'" class="checkchild" />';
            $(nRow).find(".handle-ck").append($compile(checkStr)($scope));
            
            //菜单等级
			var gradeStr = "";
			if(aData.level == 0){
				gradeStr = "一级角色";
			} else{
				gradeStr = "二级角色";
			}
            $(nRow).find(".menu-grade").append(gradeStr);
            
            //菜单状态
            var menuStatus = "";
            if(aData.status == "AVAILABLE"){
            	menuStatus = "可用";
            } else if(aData.status == "DELETE"){
            	menuStatus = "删除";
            } else if(aData.status == "FORBID"){
            	menuStatus = "禁止";
            }
            $(nRow).find(".menuStatus").append(menuStatus);
        },
        "fnDrawCallback": function(oSettings) {
            
        },
        "fnServerParams": function(aoData) {
            
        },
        "fnServerData": function(sSource,aData,fnCallback,dataTableObject) {
        	//$scope.upRole 可能为null 所以要做下判断处理 避免报错
        	var upRoleId = null;
        	if($scope.upRole!=null){
        		upRoleId = $scope.upRole.id
        	}
           var obj = dataTableObject.oAjaxData,_baseParams = {
             // 'landlordId':user.get('landlordId'),
             'page':obj.iDisplayStart / obj.iDisplayLength + 1,
             'rows':obj.iDisplayLength,
             'search':'false',
             'nd': '1494221804416',
             // 'rows': 50,
             // 'page': 1,
             'order': "asc",
             "roleName": $scope.userName,  //搜索参数 menuName：菜单搜索  tagName：关键字搜索
             "upId": upRoleId,
             "status": $scope.itemStatus.status
           };
            var __data = angular.extend({},_baseParams,obj.queryParams);
            rest.decoJava({
	           	type: 'post',
	            url: sSource,
	            data: __data,
	           	beforeSend: function(request){
					request.setRequestHeader("token", token); 
				},
	            success: function(data){
	              console.log(data);
	              $scope.myDatas = data;
	                var data1 = {
	                    'aaData': data.result,
	                    'sEcho': obj.sEcho,
	                    'iTotalDisplayRecords': data.pager.recordCount,
	                    'iTotalRecords': data.records
	                };
	                fnCallback(data1);
	                //$(dataTableObject.nScrollBody).css('overflow', 'visible');
                    //$(dataTableObject.nScrollBody).css('margin-bottom', 60 + 'px');
                    $(".dataTables_scroll").css("overflow", "auto");
        			$(".dataTables_scrollBody").css("overflow", "visible");
	            }
	        })
            //搜索 说明 只要是点击的搜索就让page为1 并且刷新datatables目的是回到第一页
		    //说明 自定义搜索只需在点击搜索的时候改变下datatables传过去的参数 然后$scope.dataTable.fnClearTable()即可
		    $scope.search = function(){
		    	__data.page = 1;
		    	$scope.tab01.fnClearTable();
		    }
         }
    }

    $scope.initFinishRole = function(dataTable) {
        $scope.tab01 = dataTable;
     }
     
    //修改角色信息
    $scope.decorateModify = function (iDisplayIndex,e) {
    	
    	//权限控制
    	var nowId = this.btns.edit;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	
        ngDialog.openConfirm({
          template: 'js/module/decorate/editRole.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/editRole.js'])
                    });
            }
          },
          data:$scope.myDatas.result[iDisplayIndex],
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
              $scope.tab01.fnClearTable();
        }, function(reason) {
              $scope.tab01.fnClearTable();
        });

    }
    $(document).on("click",".operation-btn",function(ev){
    	ev.stopPropagation();
    	$(".operation-none").hide();
    	var that = $(this).siblings(".operation-none");
    	if(that.css("display") == "none"){
    		that.show();
    	} else{
    		that.hide();
    	}
    })
    $(document).on("click",function(){
    	$(".operation-none").hide();
    })
    /*$scope.coverBgHide = function() {
        $('.operation-none').hide();
        $scope.isCoverBgShow = false;
        // $scope.$apply();
    }*/
    //分配权限
    $scope.decorateModify2 = function (e, iDisplayIndex) {
    	
    	//权限控制
    	var nowId = this.btns.jurisdiction;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	
        var btn = $(e.target);
        ngDialog.openConfirm({
          template: 'js/module/decorate/rolePermission.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/rolePermission.js'])
                    });
            }
          },
          data:$scope.myDatas.result[iDisplayIndex],
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
              $scope.tab01.fnClearTable();
        }, function(reason) {
              $scope.tab01.fnClearTable();
        });

    }
    
    //成员
    $scope.decorateModify3 = function (e, iDisplayIndex) {
    	
    	//权限控制
    	var nowId = this.btns.addmember;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	
        var btn = $(e.target);
        ngDialog.openConfirm({
          template: 'js/module/decorate/member.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/member.js'])
                    });
            }
          },
          data:$scope.myDatas.result[iDisplayIndex],
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
              $scope.tab01.fnClearTable();
        }, function(reason) {
              $scope.tab01.fnClearTable();
        });
    }
    
    //全部选中和取消
    $scope.allMenu = function(e){
    	var This = angular.element(e.target);
    	if(This.is(":checked")){
    		angular.element(".checkchild").prop("checked",true);
    	} else{
    		angular.element(".checkchild").prop("checked",false);
    	}
    }
    
    //新建角色
    $scope.newRole = function(){
    	
    	//权限控制
    	var nowId = this.btns.add;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	
    	//var btn = $(e.target);
        ngDialog.openConfirm({
          template: 'js/module/decorate/newRole.html',
          resolve: {
            load: function() {
                return $ocLazyLoad.load('angularFileUpload').then(
                    function(){
                        return uiLoad.load(['js/module/decorate/newRole.js'])
                    });
            }
          },
          data:"",
          scope: $scope,
          width: 1200,
          // height: 700
        }).then(function(data) {
              $scope.tab01.fnClearTable();
        }, function(reason) {
              $scope.tab01.fnClearTable();
        });
    }
    
    //删除
    $scope.deleteMenu = function(e){
    	
    	//权限控制
    	var nowId = this.btns.delete;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	
    	if($(".checkchild:checked").length == 0){
    		layer.msg("没有选中项", {
	        	offset:'t',
	        	icon: 2,
				time: 2000
			});
    	} else{
    		layer.msg("确定删除吗？", {
	        	offset:'t',
	        	icon: 3,
				time: 0, //不自动关闭
				btn: ['确定','取消'],
				yes: function(index){
					layer.close(index);
					//执行删除
					var idArr = [];
		    		$(".checkchild").each(function(){
			    		if($(this).is(":checked")){
			    			idArr.push($(this).val());
			    		}
			    	});
		    		rest.deco({
			            url: '/tenancy-sys/admin/role/batchDelete',
			            data: {"ids[]":idArr},
			            success: function (result) {
			            	var _result = JSON.parse(result);
			            	console.log(_result);
			            	if(_result.statusCode == "200"){
				            	layer.msg(_result.message, {
						        	offset:'t',
						        	icon: 1,
									time: 0, //不自动关闭
									btn: ['确定'],
									yes: function(index){
										layer.close(index);
										$scope.tab01.fnClearTable();
								    }
								});
							} else{
								layer.msg(_result.message, {
						        	offset:'t',
						        	icon: 5,
									time: 0, //不自动关闭
									btn: ['确定'],
									yes: function(index){
										layer.close(index);
								    }
								});
							}
			            }
			        });
			    }
			});
    	}
    };
    
    //顶部编辑
    $scope.menueditTop = function(){
    	
    	//权限控制
    	var nowId = this.btns.edit;
    	if(accessStr.indexOf(nowId) == -1){
    		layer.msg("你没有该操作权限", {
	        	offset:'t',
	        	icon: 2
			});
			return false;
    	}
    	
    	if($(".checkchild:checked").length == 0){
    		layer.msg("没有选中项", {
	        	offset:'t',
	        	icon: 2,
				time: 2000
			});
    	} else if($(".checkchild:checked").length >= 2){
    		layer.msg("一次只能编辑一项", {
	        	offset:'t',
	        	icon: 2,
				time: 2000
			});
    	} else{
    		var iDisplayIndex = parseInt($(".checkchild:checked").attr("data-index"));
    		$scope.decorateModify(iDisplayIndex)
    	}
    }

});
